<template>
    <div class="Serif-Bolder flex flex-row items-center">
        <van-tag
            class="mx-1 cursor-default"
            v-for="tag in value"
            :key="tag.name"
            :closeable="closeable"
            :type="tag.type || type"
            :size="tag.size || size"
            @close="handleClose(tag)"
        >
            {{ tag.name }}
        </van-tag>
        <input
            v-if="inputVisible"
            class="w-20 rounded shadow m-1 text-sm p-1"
            v-model="inputValue"
            ref="saveTagInput"
            @keydown.enter="handleInputConfirm"
            @blur="handleInputConfirm"
        />
        <van-button
            class="p-1 m-1 border-0 rounded outline-none"
            size="small"
            @click="showInput"
            v-show="editable"
        >
            + New Tag
        </van-button>
    </div>
</template>

<script>
export default {
    props: {
        editable: {
            default: false,
        },
        type: {
            default: "primary",
        },
        closeable: {
            default: false,
        },
        size: {
            default: "medium",
        },
        plain: {
            default: false,
        },
        value: {
            type: Array,
            default: () => [], // [{plain:true,name:"",type:"",closeable:false}]
        },
    },
    components: {},
    data() {
        return {
            inputVisible: false,
            inputValue: "",
        };
    },
    methods: {
        handleClose(tag) {
            this.$emit(
                "input",
                this.value.filter((i) => i.createAt != tag.createAt)
            );
        },

        showInput() {
            this.inputVisible = true;
            this.$nextTick(() => {
                this.$refs.saveTagInput.focus();
            });
        },

        handleInputConfirm() {
            let inputValue = this.inputValue;
            if (inputValue) {
                this.$emit("input", [
                    ...this.value,
                    { name: inputValue, createAt: new Date().getTime() },
                ]);
            }
            this.inputVisible = false;
            this.inputValue = "";
        },
    },
};
</script>

<style lang="less" scoped></style>
